/**
 *    Copyright (C) 2008, 2009  Victor Smirnov <aist11@gmail.com>
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License along
 *    with this program; if not, write to the Free Software Foundation, Inc.,
 *    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *    See LICENSE.exceptions in the root folder of this project for possible
 *    exceptions
 *
 */

package ru.teleology.cubefs.editor.model;



import ru.teleology.cubefs.api.models.Map;
import ru.teleology.cubefs.api.models.Model;
import ru.teleology.cubefs.api.models.Container;
import ru.teleology.cubefs.api.models.TreeMap;
import ru.teleology.cubefs.api.models.Map.Pair;
import ru.teleology.cubefs.api.reflection.list.StaticListOfTyped;
import ru.teleology.cubefs.api.reflection.number.Number;
import ru.teleology.cubefs.api.reflection.value.TypedIDValue;

public class RootsList {
	private final TreeMap roots;
	private final Container container;

	public RootsList(Container container) {
		this.container = container;
		this.roots = container.roots();
	}

	public TreeMap getRoots() {
		return roots;
	}
	
	public Model getCollection(long index) {
		Pair pair = roots.CreatePairHolder();
		try {
			roots.Get(index, pair);
			TypedIDValue id = (TypedIDValue) pair.value();
			return container.GetCollection(id);
		}
		finally {
			pair.destroy();
		}
	}
	
	public long getCollectionIndex(Model collection) {
		Map.Pair pair = roots.CreatePairHolder(); 
		try {
			StaticListOfTyped keys = (StaticListOfTyped) pair.key();
			Number key = (Number) keys.get(0);
			key.SetBigIntValue(collection.ModelName());
			return roots.GetKeyIndex(key);
		}
		finally {
			pair.destroy();
		}
	}
	
	public long getSize() {
		return roots.GetSize();
	}

	public Container getContainer() {
		return container;
	}
}
